<?php

class HttpProtocol
{
    public $originRequestContentString = '';

    private $originRequestContentList = [];

    private $originRequestContentMap = [];

    private $responseHead = [
        'http' => 'HTTP/1.1 200 OK',
        'content-type' => 'Content-Type: text/html',
        'server' => 'Server: php/0.0.1'
    ];

    private $responseBody = '';

    public $responseData = '';

    public function request($content = '')
    {
        if (empty($content)) {
            throw new Exception('content is empty');
        }
        $this->originRequestContentString = $content;
        $this->originRequestContentList = explode('\r\n', $this->originRequestContentString);
        if (empty($this->originRequestContentList)) {
            throw new Exception('content is empty');
        }
        foreach ($this->originRequestContentList as $k=>$v) {
            if (!$v) continue;
            if ($k === 0) {
                // 解析http method/request_uri/version
                list($http_method, $http_request_uri, $http_version) = explode(' ', $v);
                $this->originRequestContentMap['Method'] = $http_method;
                $this->originRequestContentMap['Request-Uri'] = $http_request_uri;
                $this->originRequestContentMap['Version'] = $http_version;
                continue;
            }
            list($key, $val) = explode(': ', $v);
            $this->originRequestContentMap[$key] = $val;
        }
    }

    public function response($responseBody)
    {
        //$count = count($this->responseHead);
        $finalHead = '';
        foreach ($this->responseHead as $v) {
            $finalHead .= $v."\r\n";
        }
        $this->responseData = $finalHead."\r\n".$responseBody;
    }
}